/*
 * BanBu_ChatBackgroundSettingViewController
 * @description 本文件提供更换聊天背景图片界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供更换聊天背景图片界面的ViewController
 */

#import "BanBu_ChatBackgroundSettingViewController.h"
#import "AppDataManager.h"
#import <QuartzCore/QuartzCore.h>
#import "SCGIFImageView.h"
#import "BanBu_ChatBgCell.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "BanBu_ThemeManager.h"
#import "BanBuAPIs.h"
#import "UIViewController+Animation.h"
#import "BanBu_PhotoViewController.h"

@interface BanBu_ChatBackgroundSettingViewController ()

@end

@implementation BanBu_ChatBackgroundSettingViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self)
    {
        // Custom initialization
    }
    return self;
}

-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}

//重新下载
-(void)btn_refresh:(UIButton *)sender
{
    [self setDefaultGif:self.backgroundGIFArray.count];
    [self setDefaultImage:self.backgroundImageArray.count];
    
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    [FileManager removeItemAtPath:self.imagePath error:nil];
    
    [FileManager removeItemAtPath:self.GIFPath error:nil];
    
    [self getMore];
}

-(void)setDefaultGif:(NSInteger)bubbleCount
{
    NSLog(@"动态图:%d",bubbleCount);
    [self.backgroundGIFArray removeAllObjects];
    
    for (int i = 0; i<bubbleCount; i++)
    {
        [self.backgroundGIFArray addObject:@"bg_default.png"];
    }
}

-(void)setDefaultImage:(NSInteger)bubbleCount
{
    NSLog(@"静态图:%d",bubbleCount);
    [self.backgroundImageArray removeAllObjects];
    
    for (int i = 0; i<bubbleCount; i++)
    {
        [self.backgroundImageArray addObject:@"bg_default.png"];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setBGImage:) name:@"setBGImage" object:nil];
    
    ThemeManager.chatBGView = self;
    
    BanBu_NavButton *btn_refresh = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    btn_refresh.position = ButtonPositionRight;
    btn_refresh.frame=CGRectMake(0, 0,40, 30);
    [btn_refresh addTarget:self action:@selector(btn_refresh:) forControlEvents:UIControlEventTouchUpInside];
    [btn_refresh setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
    btn_refresh.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *cancelItem = [[[UIBarButtonItem alloc] initWithCustomView:btn_refresh] autorelease];
    self.navigationItem.rightBarButtonItem = cancelItem;
    [btn_refresh release];
    
    
    UIImage * selectedImage = [UIImage imageNamed:@"ResultIconSuccess@2x.png"];
    self.selectedImageView = [[[UIImageView alloc]init] autorelease];
    self.selectedImageView.image = selectedImage;
    
    self.title = NSLocalizedString(@"chatBackgroundImage", nil);
    
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor colorWithRed:200.0/255 green:200.0/255 blue:200.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc]initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];
    if(img.image)
    {
        self.tableView.backgroundView = img;
    }
    
    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height)];
    
    [self initTableViewHeader];
    
    
    self.backgroundImageArray = [NSMutableArray arrayWithCapacity:20];
    self.backgroundGIFArray = [NSMutableArray arrayWithCapacity:20];

    NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] ;

    
    self.imagePath = [fileName stringByAppendingPathComponent:@"chat_bg_photo"];
    self.GIFPath = [fileName stringByAppendingPathComponent:@"chat_bg_GIF"];
    
    if (![[NSFileManager defaultManager ] fileExistsAtPath:self.imagePath])
    {
        [[NSFileManager defaultManager]createDirectoryAtPath:self.imagePath withIntermediateDirectories:YES attributes:nil error:nil];//创建静态图文件夹
    }
    //静态图
    self.imageFilePath = [self.imagePath stringByAppendingPathComponent:@"bgInfo.plist"];
    
    [self getDefault];
    
    NSDictionary * ImageDic = [NSDictionary dictionaryWithContentsOfFile:self.imageFilePath];
    
    for(int i =0 ;i < ImageDic.count; i++)
    {
        NSDictionary * imageInfoDic = [ImageDic valueForKey:[NSString stringWithFormat:@"chat_bg_%02d",i]];
        if ([imageInfoDic valueForKey:@"bgNameicon"])
        {
            [self.backgroundImageArray addObject:[imageInfoDic valueForKey:@"bgNameicon"]];
        }
    }

    //动态图    
    if (![[NSFileManager defaultManager ] fileExistsAtPath:self.GIFPath])
    {
        [[NSFileManager defaultManager]createDirectoryAtPath:self.GIFPath withIntermediateDirectories:YES attributes:nil error:nil];//创建动态图文件夹
    }
    
    self.GIFFilePath = [self.GIFPath stringByAppendingPathComponent:@"GIFInfo.plist"];
    ImageDic = [NSDictionary dictionaryWithContentsOfFile:self.GIFFilePath];
    for(int i =0 ;i < ImageDic.count; i++)
    {
        NSDictionary * imageInfoDic = [ImageDic valueForKey:[NSString stringWithFormat:@"chat_bg_%d",i]];
        if ([imageInfoDic valueForKey:@"bgNameicon"])
        {
            [self.backgroundGIFArray addObject:[imageInfoDic valueForKey:@"bgNameicon"]];
        }
    }
    //直接加载
    [self getMore];
}

-(void)initTableViewHeader
{
    UIView *backView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 290, 154)]autorelease];
    backView.backgroundColor = [UIColor clearColor];
    
    //加载提示头
    UITextView * headerText = [[UITextView alloc]initWithFrame:CGRectMake(15, 25, 290, 50)];
    headerText.backgroundColor = [UIColor whiteColor];
    headerText.font = [UIFont boldSystemFontOfSize:15];
    headerText.textColor = [UIColor darkGrayColor];
    headerText.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    headerText.layer.borderWidth = .8;
    headerText.userInteractionEnabled = NO;
    headerText.editable = NO;
    headerText.layer.cornerRadius = 8.0;
    headerText.textAlignment = kTextAlignmentCenter;
    
    headerText.text = NSLocalizedString(@"helpfulTitle", nil);
    
    headerText.text =[headerText.text stringByAppendingFormat:@"\n%@",NSLocalizedString(@"chooseWhitchYouLike", nil)];
    [backView addSubview:headerText];
    [headerText release];
    
    BanBu_NavButton * headerButton = [[BanBu_NavButton alloc]initWithButtonType:UIButtonCreatTypeCustomBtn];
    headerButton.tintColor = [UIColor blackColor];
    
    [headerButton setFrame:CGRectMake(15, 92, 290, 50)];
    [headerButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    
    [headerButton setBackgroundImage:[[UIImage imageNamed:@"app_btn_blue.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
    
    [headerButton setTitle:[NSString stringWithFormat:@"　%@",NSLocalizedString(@"btnChooseFromAlbum", nil)] forState:UIControlStateNormal];
    [headerButton addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside];
    
    [backView addSubview:headerButton];
    
    
    UIButton * button = [UIButton buttonWithType: UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"profileios.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside];
    button.frame=CGRectMake(290, 109, 10, 16);
    [backView addSubview:button];
    self.tableView.tableHeaderView = backView;
    [headerButton release];
}

-(void)viewDidAppear:(BOOL)animated
{
    [self setSelected:MyAppDataManager.selectedBgIndex];
    
    if (self.backgroundImageArray.count==0)
    {
        self.selectedImageView.frame = CGRectMake(0, 0, 0, 0);
    }
    [self.tableView addSubview:self.selectedImageView];

}
-(void)viewWillDisappear:(BOOL)animated
{
    if (MyAppDataManager.selectedBgIndex <2000)
    {
        MyAppDataManager.selectedBgIndex = [[UserDefaults valueForKey:@"selectedBgIndex"] integerValue];    
    }
    self.navigationController.view.userInteractionEnabled = YES;
    [self dismissModalView];
    ThemeManager.chatBGView = nil;
}

-(void)getDefault
{
    NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] ;
    self.imagePath = [fileName stringByAppendingPathComponent:@"chat_bg_photo"];
    self.imageFilePath = [self.imagePath stringByAppendingPathComponent:@"bgInfo.plist"];
    
    if (![[NSFileManager defaultManager ] fileExistsAtPath:self.imagePath])
    {
        [[NSFileManager defaultManager]createDirectoryAtPath:self.imagePath withIntermediateDirectories:YES attributes:nil error:nil];//创建静态图文件夹
    }

    NSString * bubble_0 = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"]stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"chat_bg_photo"];
    
    NSString * fileString = [[NSBundle mainBundle]pathForResource:@"chat_bg_00" ofType:@"jpg"];
    
    NSString * toPath =[bubble_0 stringByAppendingPathComponent:@"chat_bg_00.jpg"];
    
    if ([[NSFileManager defaultManager]fileExistsAtPath:toPath])
    {
        return;
    }
    
    [[NSFileManager defaultManager]copyItemAtPath:fileString toPath:toPath error:nil];
    
    fileString = [[NSBundle mainBundle]pathForResource:@"chat_bg_00_icon@2x" ofType:@"png"];
    
    toPath = [bubble_0 stringByAppendingPathComponent:@"chat_bg_00_icon@2x.png"];
    
    [[NSFileManager defaultManager]copyItemAtPath:fileString toPath:toPath error:nil];
    
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"chat_bg_00.jpg",@"bgName",@"chat_bg_00_icon@2x.png",@"bgNameicon",[NSNumber numberWithInt:0],@"id",nil ];
    NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    
    if ([[NSFileManager defaultManager]fileExistsAtPath:self.imageFilePath])
    {
        dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:self.imageFilePath];
    }
    [dictionary setValue:dic forKey:@"chat_bg_00"];
    [dictionary writeToFile:self.imageFilePath atomically:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.backgroundGIFArray.count==0)
    {
        return 1;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    
    if(section == 0)
    {
        if (self.backgroundGIFArray.count)
        {
            return ceilf(self.backgroundGIFArray.count/3.0);
        }
        else
        {
            return ceilf(self.backgroundImageArray.count/3.0);
        }
    }

    tableView.separatorColor  =[UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    return ceilf(self.backgroundImageArray.count/3.0);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    backView.backgroundColor = [UIColor clearColor];
    UILabel *headerTitle = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 300, 30)];
    headerTitle.backgroundColor = [UIColor clearColor];
    
    headerTitle.font = [UIFont systemFontOfSize:14];
    headerTitle.textColor = [UIColor darkGrayColor];
    if (section ==1)
    {
        headerTitle.text = NSLocalizedString(@"recommendBackground", nil);
    }
    else if(section == 0)
    {
        if (self.backgroundGIFArray.count)
        {
            headerTitle.text = NSLocalizedString(@"GIFBackground", nil);
        }
        else
        {
            headerTitle.text = NSLocalizedString(@"recommendBackground", nil);
        }
    }
    
    [backView addSubview:headerTitle];
    [headerTitle release];
    return [backView autorelease];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    BanBu_ChatBgCell *cell = (BanBu_ChatBgCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
    {
        cell = [[[BanBu_ChatBgCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];        
    }
    cell.backgroundColor = [UIColor clearColor];
    if(indexPath.section == 1)
    {
        cell.textLabel.text = @"";
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell setType:1];//设置为静态背景
        
        //默认图片
        if ([[self.backgroundImageArray objectAtIndex:(0 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])
        {
            cell.imageView1.image = [UIImage imageNamed:@"bg_default.png"];
        }
        else
        {
            cell.imageView1.image = [UIImage imageWithContentsOfFile:[self.imagePath stringByAppendingPathComponent:[self.backgroundImageArray objectAtIndex:0 + indexPath.row * 3]]];
        }
        
        cell.imageView1.tag = 1 + indexPath.row * 3;
        
        UITapGestureRecognizer * tap1 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
        [cell.imageView1 addGestureRecognizer:tap1];
        
        
        if (indexPath.row*3+1 < self.backgroundImageArray.count)
        {
            cell.imageView2.hidden = NO;
            if ([[self.backgroundImageArray objectAtIndex:(1 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])
            {
                cell.imageView2.image = [UIImage imageNamed:@"bg_default.png"];
            }
            else
            {
                cell.imageView2.image = [UIImage imageWithContentsOfFile:[self.imagePath stringByAppendingPathComponent:[self.backgroundImageArray objectAtIndex:1 + indexPath.row * 3]]];
            }
            cell.imageView2.tag = 2 + indexPath.row * 3;
            
            UITapGestureRecognizer * tap2 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
            
            [cell.imageView2 addGestureRecognizer:tap2];
        }
        else
        {
            cell.imageView2.hidden = YES;
        }
        
        if (indexPath.row*3+2 < self.backgroundImageArray.count)
        {
            cell.imageView3.hidden = NO;
            if ([[self.backgroundImageArray objectAtIndex:(2 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])
            {
                cell.imageView3.image = [UIImage imageNamed:@"bg_default.png"];
            }
            else
            {
                cell.imageView3.image = [UIImage imageWithContentsOfFile:[self.imagePath stringByAppendingPathComponent:[self.backgroundImageArray objectAtIndex:2 + indexPath.row * 3]]];
            }

            cell.imageView3.tag  = 3 + indexPath.row * 3;
            
            UITapGestureRecognizer * tap3 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
            
            [cell.imageView3 addGestureRecognizer:tap3];
        }
        else
        {
            cell.imageView3.hidden = YES;
        }
    }
    else
    {
        if (self.backgroundGIFArray.count)
        {
            cell.textLabel.text = @"";
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell setType:2];//设置动态背景
            
            NSString *path1 = nil;
            if ([[self.backgroundGIFArray objectAtIndex:(0 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])//默认图
            {
                path1 = [[NSBundle mainBundle]pathForResource:@"bg_default" ofType:@"png"];
            }
            else
            {
                path1 = [self.GIFPath stringByAppendingPathComponent:[self.backgroundGIFArray objectAtIndex:(0 + indexPath.row * 3)]];
            }
            
            
            cell.GIFImageView1.gifFile = path1;
            cell.GIFImageView1.userInteractionEnabled = YES;
            cell.GIFImageView1.tag = -(1 + indexPath.row * 3);
            
            UITapGestureRecognizer * tap1 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
            [cell.GIFImageView1 addGestureRecognizer:tap1];
            
            if (indexPath.row*3+1 < self.backgroundGIFArray.count)
            {
                cell.GIFImageView2.hidden = NO;
                
                NSString *path2 = nil;
                if ([[self.backgroundGIFArray objectAtIndex:(0 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])//默认图
                {
                    path2 = [[NSBundle mainBundle]pathForResource:@"bg_default" ofType:@"png"];
                }
                else
                {
                    path2 = [self.GIFPath stringByAppendingPathComponent:[self.backgroundGIFArray objectAtIndex:(1 + indexPath.row * 3)]];
                }
                
                cell.GIFImageView2.gifFile = path2;
                cell.GIFImageView2.userInteractionEnabled = YES;
                cell.GIFImageView2.tag = -(2 + indexPath.row * 3);
                
                UITapGestureRecognizer * tap2 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
                [cell.GIFImageView2 addGestureRecognizer:tap2];
            }
            else
            {
                cell.GIFImageView2.hidden = YES;
            }
            if (indexPath.row*3+2 < self.backgroundGIFArray.count)
            {
                cell.GIFImageView3.hidden = NO;
                
                NSString *path3 = nil;
                if ([[self.backgroundGIFArray objectAtIndex:(0 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])//默认图
                {
                    path3 = [[NSBundle mainBundle]pathForResource:@"bg_default" ofType:@"png"];
                }
                else
                {
                    path3 = [self.GIFPath stringByAppendingPathComponent:[self.backgroundGIFArray objectAtIndex:(2 + indexPath.row * 3)]];
                }
                
                cell.GIFImageView3.gifFile = path3;
                cell.GIFImageView3.userInteractionEnabled = YES;
                cell.GIFImageView3.tag = -(3 + indexPath.row * 3);
                
                UITapGestureRecognizer * tap3 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
                [cell.GIFImageView3 addGestureRecognizer:tap3];
            }
            else
            {
                cell.GIFImageView3.hidden = YES;
            }
        }
        else
        {
            cell.textLabel.text = @"";
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell setType:1];//设置为静态背景
            if ([[self.backgroundImageArray objectAtIndex:(0 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])
            {
                cell.imageView1.image = [UIImage imageNamed:@"bg_default.png"];
            }
            else
            {
                cell.imageView1.image = [UIImage imageWithContentsOfFile:[self.imagePath stringByAppendingPathComponent:[self.backgroundImageArray objectAtIndex:0 + indexPath.row * 3]]];
            }            cell.imageView1.tag = 1 + indexPath.row * 3;
            
            UITapGestureRecognizer * tap1 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
            [cell.imageView1 addGestureRecognizer:tap1];
            
            
            if (indexPath.row*3+1 < self.backgroundImageArray.count)
            {
                cell.imageView2.hidden = NO;
                if ([[self.backgroundImageArray objectAtIndex:(1 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])
                {
                    cell.imageView2.image = [UIImage imageNamed:@"bg_default.png"];
                }
                else
                {
                    cell.imageView2.image = [UIImage imageWithContentsOfFile:[self.imagePath stringByAppendingPathComponent:[self.backgroundImageArray objectAtIndex:1 + indexPath.row * 3]]];
                }                cell.imageView2.tag = 2 + indexPath.row * 3;
                
                UITapGestureRecognizer * tap2 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
                
                [cell.imageView2 addGestureRecognizer:tap2];
            }
            else
            {
                cell.imageView2.hidden = YES;
            }
            
            if (indexPath.row*3+2 < self.backgroundImageArray.count)
            {
                cell.imageView3.hidden = NO;
                if ([[self.backgroundImageArray objectAtIndex:(2 + indexPath.row * 3)] isEqualToString:@"bg_default.png"])
                {
                    cell.imageView3.image = [UIImage imageNamed:@"bg_default.png"];
                }
                else
                {
                    cell.imageView3.image = [UIImage imageWithContentsOfFile:[self.imagePath stringByAppendingPathComponent:[self.backgroundImageArray objectAtIndex:2 + indexPath.row * 3]]];
                }                cell.imageView3.tag  = 3 + indexPath.row * 3;
                
                UITapGestureRecognizer * tap3 = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleChoose:)] autorelease];
                
                [cell.imageView3 addGestureRecognizer:tap3];
            }
            else
            {
                cell.imageView3.hidden = YES;
            }
        }
    }
    
    return cell;
}


#pragma mark - Table view delegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        //从相册中选择；
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [picker setAllowsEditing:NO];

        [self presentViewController:picker animated:YES];
        [picker release];
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

-(void)pushNext:(UIButton *)button
{
    //从相册中选择；
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [picker setAllowsEditing:NO];
    
    [self presentViewController:picker animated:YES];
    [picker release];   
}

#pragma mark  -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo
{
    NSString *imagePathExtension = nil;
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        imagePathExtension = @"jpg";
    else
    {
        imagePathExtension = [[[editingInfo valueForKey:UIImagePickerControllerReferenceURL] pathExtension] lowercaseString];
        if([imagePathExtension isEqualToString:@"gif"])
            imagePathExtension = @"jpg";
    }
    
    NSData *data = nil;
    image=[MyAppDataManager scaleImage:image proportion:1];
    
    if([imagePathExtension isEqualToString:@"png"])
        data = UIImagePNGRepresentation(image);
    else
        data = UIImageJPEGRepresentation(image, .6);
//    [UserDefaults setValue:data forKey:ChatBackImageData];
    BanBu_PhotoViewController * photo = [[BanBu_PhotoViewController alloc]init];
    photo.image = [UIImage imageWithData:data];
    photo.picker = picker;
    photo.enablePost = NO;
    [picker setNavigationBarHidden:YES animated:YES];
    [picker pushViewController:photo animated:YES];
    [photo release];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES];
}

-(void)setBGImage:(NSNotification *)notifi
{
    self.imageView.image = [[notifi object] valueForKey:@"image"];
    MyAppDataManager.selectedBgIndex = 99999;
    NSData * imagedata = UIImagePNGRepresentation(self.imageView.image);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString * chatBackPath = [[paths objectAtIndex:0] stringByAppendingString:@"/chatbackImage.png"];
    BOOL result = [imagedata writeToFile:chatBackPath atomically:YES];
    if (result)
    {
        NSLog(@"保存成功");
    }
//    [UserDefaults setValue:imagedata forKey:ChatBackImageData];
//    [UserDefaults synchronize];
    UIAlertView * alert = [[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"conform", nil) message:NSLocalizedString(@"alertTitle", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"reChoose", nil) otherButtonTitles:NSLocalizedString(@"returnConform", nil), nil] autorelease];
    [alert show];
}

//点击图片事件
-(void)singleChoose:(UITapGestureRecognizer *)tap
{
    
    NSInteger tag = tap.view.tag;

    MyAppDataManager.selectedBgIndex = tag;
    
    NSString * JOrD = @"";
    
    if (tag>0)
    {
        JOrD = @"j";
        [ThemeManager downloadBigPhoto:[NSString stringWithFormat:@"%02d",abs(MyAppDataManager.selectedBgIndex)-1] andPhotoType:JOrD];
    }
    else
    {
        JOrD = @"d";
        [ThemeManager downloadBigPhoto:[NSString stringWithFormat:@"%d",abs(MyAppDataManager.selectedBgIndex)-1] andPhotoType:JOrD];
    }
    
    
    
    [self setSelected:tag];
    
    self.navigationController.view.userInteractionEnabled = NO;
    
    UIAlertView * alert = [[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"conform", nil) message:NSLocalizedString(@"alertTitle", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"reChoose", nil) otherButtonTitles:NSLocalizedString(@"returnConform", nil), nil] autorelease];
    
    [alert performSelector:@selector(show) withObject:nil afterDelay:0.25];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0://取消
        {
            MyAppDataManager.selectedBgIndex = [[UserDefaults valueForKey:@"selectedBgIndex"] integerValue];
          
            [UserDefaults setValue:nil forKey:ChatBackImageData];
            [self setSelected:MyAppDataManager.selectedBgIndex];
        }
            break;
        case 1://确认
        {
            NSLog(@"%d",MyAppDataManager.selectedBgIndex);
            [self setSelected:MyAppDataManager.selectedBgIndex];
            [UserDefaults setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBgIndex] forKey:@"selectedBgIndex"];
            
            [self.navigationController popViewControllerAnimated:YES];
        }

            break;
            
        default:
            break;
    }
    
    self.navigationController.view.userInteractionEnabled = YES;
}

-(void)setSelected:(NSInteger )tagValue
{
    if (tagValue < 0)//动态图
    {
        NSInteger tag = MyAppDataManager.selectedBgIndex + 1;
        tag = -tag;
        NSInteger row = tag / 3;
        NSInteger i = tag % 3;
        
        [self.selectedImageView setFrame:CGRectMake(i*100+24, row * 100+119 + 80, 72, 72)];
    }
    else//静态图
    {
        if (self.backgroundGIFArray.count)
        {
            NSInteger tag = MyAppDataManager.selectedBgIndex - 1;
            if (tag<0)
            {
                tag = 0;
            }
            NSInteger row = tag / 3;
            NSInteger i = tag % 3;
            [self.selectedImageView setFrame:CGRectMake(i*100+24, (row + ceil(self.backgroundGIFArray.count/3.0))*100+148 + 80, 72, 72)];
        }
        else
        {
            NSInteger tag = MyAppDataManager.selectedBgIndex - 1;
            if (tag<0)
            {
                tag = 0;
            }
            
            NSInteger row = tag / 3;
            NSInteger i = tag % 3;
            [self.selectedImageView setFrame:CGRectMake(i*100+24, row*100+119 + 80, 72, 72)];
        }
    }
}

//获取背景
-(void)getMore
{
    [ThemeManager getMore:BanBu_GetBGMoreList];
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
}

-(void)dismissModalView
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.5];
}


//刷新界面
-(void)refreshView
{
    NSDictionary * ImageDic = [NSDictionary dictionaryWithContentsOfFile:self.imageFilePath];
    
    for(int i =0 ;i < ImageDic.count; i++)
    {
        NSDictionary * imageInfoDic = [ImageDic valueForKey:[NSString stringWithFormat:@"chat_bg_%02d",i]];
        if (imageInfoDic && self.backgroundImageArray.count > i)
        {
            [self.backgroundImageArray replaceObjectAtIndex:i withObject:[imageInfoDic valueForKey:@"bgNameicon"]];
        }
    }
    
    //动态图
    
    ImageDic = [NSDictionary dictionaryWithContentsOfFile:self.GIFFilePath];
    for(int i =0 ;i < ImageDic.count; i++)
    {
        NSDictionary * imageInfoDic = [ImageDic valueForKey:[NSString stringWithFormat:@"chat_bg_%d",i]];
        if (imageInfoDic && self.backgroundGIFArray.count > i)
        {
            [self.backgroundGIFArray replaceObjectAtIndex:i withObject:[imageInfoDic valueForKey:@"bgNameicon"]];
        }
    }
    
    [self.tableView reloadData];
}


-(void)dealloc
{
    [_selectedImageView release],_selectedImageView = nil;
    [_backgroundImageArray release],_backgroundImageArray = nil;
    [_backgroundGIFArray release],_backgroundGIFArray= nil;
    [_imageView release],_imageView= nil;
    
    [_imageFilePath release],_imageFilePath = nil;
    [_imageDownPath release],_imageDownPath = nil;
    
    [_GIFFilePath release],_GIFDownPath = nil;
    [_GIFDownPath release],_GIFDownPath = nil;
    [_imagePath release],_imagePath = nil;
    [_GIFPath release],_GIFPath = nil;
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"setBGImage" object:nil];
    
    [super dealloc];
}
@end
